#include"Image.h"

Image::Image():Bf(),Bi(),Matrix() {}

Image::Image(int h, int w, RGBA val):Matrix(h,w,val) {
	Bi.biWidth = w;
	Bi.biHeight = h;
	Bi.biBitCount = 32;
	Bi.biSize = 40;
	Bi.biPlanes = 1;
	Bi.biCompression = 0;
	Bi.biClrUsed = 0;
	Bi.biClrImportant = 0;
	Bi.biXPelsPerMeter = 0;
	Bi.biYPelsPerMeter = 0;
	Bi.biSizeImage = Bi.biWidth * 4 * Bi.biHeight;
	Bf.bfType = 0X4D42;
	Bf.bfSize = Bi.biSizeImage + 14;
	Bf.bfReserved1 = Bf.bfReserved2 = 0;
	Bf.bfOffBits = 14 + 40;
}

Image::Image(BITMAPFILEHEADER bf, BITMAPINFOHEADER bi, int h, int w):Bf(bf),Bi(bi),Matrix(h,w) {}

Image::Image(BITMAPFILEHEADER bf, BITMAPINFOHEADER bi, const Matrix& m):Matrix(m) {
	if (bi.biWidth != m.getWidth() || bi.biHeight != m.getWidth()) {
		//qDebug()<<"Error:";
		std::cout << "Error" << std::endl;
	}
	Bf = bf;
	Bi = bi;
}

void Image::Swap(Image& a, Image& b){
	std::swap(a.Bf, b.Bf);
	std::swap(a.Bi, b.Bi);
	Matrix::Swap(a, b);
}

Image& Image::ReadBmp(std::string filePath){
	std::locale::global(std::locale(""));
	std::fstream bmp(filePath, std::ios::binary | std::ios::in);
	std::locale::global(std::locale("C"));

	BITMAPFILEHEADER bf;
	BITMAPINFOHEADER bi;

	bmp.read((char*)&bf, sizeof(BITMAPFILEHEADER));
	bmp.read((char*)&bi, sizeof(BITMAPINFOHEADER));
	std::cout << bi.biHeight << " " << bi.biWidth << std::endl;
	Image* img = new Image(bf, bi, bi.biHeight, bi.biWidth);
	for (int i = 0; i < img->getHeight() * img->getWidth(); ++i) {
		BYTE m[4];
		bmp.read((char*)m, 4);
		RGBA t(m[0], m[1], m[2], m[3]);
		img->Set(i/bi.biWidth, i%bi.biWidth,t);
	}

	return *img;
}

void Image::WriteBmp(std::string filePath){

	std::locale::global(std::locale(""));
	std::fstream bmp(filePath, std::ios::binary | std::ios::out);
	std::locale::global(std::locale("C"));

	bmp.write((char*)&Bf, sizeof(BITMAPFILEHEADER));
	bmp.write((char*)&Bi, sizeof(BITMAPINFOHEADER));
	for (int i = 0; i < Bi.biWidth * Bi.biHeight; ++i) {
		bmp.write((char*)&(this->data[i/Bi.biWidth][i%Bi.biWidth]), 4);
	}

	bmp.close();
}
